package com.example.file_management.handler;

import com.example.file_management.pojo.material.Resource.ResourceType;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 自定义 TypeHandler，用于处理 ResourceType 枚举与数据库字符串之间的转换
 */
@MappedTypes(ResourceType.class)
public class ResourceTypeHandler extends BaseTypeHandler<ResourceType> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, ResourceType parameter, JdbcType jdbcType) throws SQLException {
        // 将 ResourceType 枚举值转换为字符串并存储到数据库
        ps.setString(i, parameter.name());
    }

    @Override
    public ResourceType getNullableResult(ResultSet rs, String columnName) throws SQLException {
        // 从 ResultSet 中读取字符串并转换为 ResourceType 枚举
        String type = rs.getString(columnName);
        return ResourceType.valueOf(type);
    }

    @Override
    public ResourceType getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        // 从 ResultSet 中读取字符串并转换为 ResourceType 枚举
        String type = rs.getString(columnIndex);
        return ResourceType.valueOf(type);
    }

    @Override
    public ResourceType getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        // 从 CallableStatement 中读取字符串并转换为 ResourceType 枚举
        String type = cs.getString(columnIndex);
        return ResourceType.valueOf(type);
    }
}